import React from 'react';
import { Form, Input, Button, Select, DatePicker, message } from 'antd';
import { useNavigate } from 'react-router-dom';
import { scheduleService, ScheduledTask } from '../../services/schedule.service';
import moment from 'moment';

const { Option } = Select;

interface ScheduleFormData {
  name: string;
  task_type: 'data_sync' | 'notification' | 'reminder';
  status: 'active' | 'paused' | 'completed';
  next_run: Date;
  // 其他必要字段
}

export default function NewSchedule() {
  const [form] = Form.useForm();
  const navigate = useNavigate();

  const onFinish = async (values: ScheduleFormData) => {
    try {
      // Format next_run to string before sending to API
      const formattedValues = {
        ...values,
        next_run: values.next_run instanceof Date 
          ? values.next_run.toISOString() 
          : moment(values.next_run).format('YYYY-MM-DD HH:mm:ss')
      };
      
      await scheduleService.create(formattedValues);
      message.success('定时任务创建成功');
      navigate('/schedule/list');
    } catch (error) {
      message.error('创建失败，请重试');
      console.error(error);
    }
  };

  return (
    <div style={{ padding: 24 }}>
      <h2>新建定时任务</h2>
      <Form
        form={form}
        layout="vertical"
        onFinish={onFinish}
        style={{ maxWidth: 600 }}
      >
        <Form.Item
          name="name"
          label="任务名称"
          rules={[{ required: true, message: '请输入任务名称' }]}
        >
          <Input placeholder="请输入任务名称" />
        </Form.Item>

        <Form.Item
          name="task_type"
          label="任务类型"
          rules={[{ required: true, message: '请选择任务类型' }]}
        >
          <Select placeholder="请选择任务类型">
            <Option value="data_sync">数据同步</Option>
            <Option value="notification">通知</Option>
            <Option value="reminder">提醒</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          initialValue="active"
        >
          <Select>
            <Option value="active">激活</Option>
            <Option value="paused">暂停</Option>
            <Option value="completed">完成</Option>
          </Select>
        </Form.Item>

        <Form.Item
          name="next_run"
          label="下次执行时间"
          rules={[{ required: true, message: '请选择下次执行时间' }]}
        >
          <DatePicker showTime format="YYYY-MM-DD HH:mm:ss" />
        </Form.Item>

        {/* 根据需要添加更多表单项 */}

        <Form.Item>
          <Button type="primary" htmlType="submit">
            创建
          </Button>
          <Button style={{ marginLeft: 8 }} onClick={() => navigate('/schedule/list')}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
} 